package com.lwm.mybatis.custom.sqlsession.defaults;

import com.lwm.mybatis.custom.cfg.Configuration;
import com.lwm.mybatis.custom.proxy.MapperProxy;
import com.lwm.mybatis.custom.sqlsession.SqlSession;
import com.lwm.mybatis.custom.utils.DataSourceUtil;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 默认的SqlSession实现类
 *
 * @author liweimin
 * @date 2021/6/15 18:08
 * @see com.lwm.mybatis.custom.sqlsession.SqlSession
 * @since
 */
public class DefaultSqlSession implements SqlSession {

    private Connection connection;

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
        this.connection = DataSourceUtil.createConnection(configuration);
    }

    @Override
    public <T> T getMapper(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new MapperProxy(configuration.getMappers(), connection));
    }

    @Override
    public void close() {
        if (connection == null) {
            return;
        }
        try {
            if (connection.isClosed()) {
                throw new RuntimeException("连接已关闭");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
